﻿using AutoMapper.Internal.Mappers;
using Humanizer;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystemDto.CustomerOrderDto;
using ThridGroup.ERP.DTO.ProductionSystemDto.ProductionMaterialReturnDto;
using ThridGroup.ERP.HumanResources;
using ThridGroup.ERP.ProductionSystem;

namespace ThridGroup.ERP.Web.Controllers.ProductionSystem
{
    [Route("ProductionSystem/ProductionManagement/[action]")]
    /// <summary>
    /// 生产管理控制器
    /// </summary>
    public class ProductionManagementController : Controller
    {
        /// <summary>
        /// 客户订单
        /// </summary>
        private readonly ICustomerOrderServices _customerOrderServices;
        
        /// <summary>
        /// 生产退料
        /// </summary>
        private readonly IProductionMaterialReturnServices _productionMaterialReturnServices;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="customerOrderServices">客户订单</param>
        /// <param name="productionMaterialReturnServices">生产退料</param>
        public ProductionManagementController(
            ICustomerOrderServices customerOrderServices,
            IProductionMaterialReturnServices productionMaterialReturnServices)
        {
            _customerOrderServices = customerOrderServices;
            _productionMaterialReturnServices = productionMaterialReturnServices;
        }

        /// <summary>
        /// 客户订单页面
        /// </summary>
        /// <returns></returns>
        public IActionResult CustomerOrderView()
        {
            return View();
        }

        /// <summary>
        /// 添加客户订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateCustomerOrder([FromBody] CustomerOrderlistDto dto)
        {
            var result = await _customerOrderServices.CreateCustomerOrder(dto);
            return Json(new
            {
                success = result > 0,
                message = result > 0 ? "添加成功" : "添加失败"
            });
        }

        /// <summary>
        /// 查询客户订单
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryCustomerOrder(GetCustomerOrderDto queryDto)
        {
            var list = await _customerOrderServices.QueryCustomerOrder(queryDto);
            // 分页处理（如有需要可调整）
            var paged = list.OrderByDescending(a => a.Id)
                            .Skip((queryDto.page - 1) * queryDto.limit)
                            .Take(queryDto.limit)
                            .ToList();
            return Json(new
            {
                code = 0,
                msg = "",
                count = list.Count,
                data = paged
            });
        }

        /// <summary>
        /// 修改客户订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateCustomerOrder([FromBody] UpdateCustomerOrderDto dto)
        {
            var result = await _customerOrderServices.UpdateCustomerOrder(dto);
            return Json(new
            {
                success = result > 0,
                message = result > 0 ? "修改成功" : "修改失败"
            });
        }

        /// <summary>
        /// 批量删除客户订单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDeleteCustomerOrder([FromBody] List<int> ids)
        {
            if (ids == null || !ids.Any())
                return Json(new { code = 1, msg = "未传递ID" });
            await _customerOrderServices.BatchDeleteCustomerOrder(ids);
            return Json(new { code = 0, msg = "删除成功" });
        }

        /// <summary>
        /// 显示客信息
        /// </summary>
        /// <param name="canGetCustomerDto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryCustomer(GetCustomerDto canGetCustomerDto)
        {
            var list = await _customerOrderServices.QueryCustomer(canGetCustomerDto);
            // 分页处理（如有需要可调整）
            var paged = list.OrderByDescending(a => a.Id)
                            .Skip((canGetCustomerDto.page - 1) * canGetCustomerDto.limit)
                            .Take(canGetCustomerDto.limit)
                            .ToList();
            return Json(new
            {
                code = 0,
                msg = "",
                count = list.Count,
                data = paged
            });
        }

        /// <summary>
        /// 导出客户订单数据到Excel
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="exportAll">是否导出全部，默认false</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportExcel([FromQuery] GetCustomerOrderDto query, bool exportAll = false)
        {
            try
            {
                byte[] data = null;
                string t = "客户订单信息.xlsx";

                // 获取数据
                var list = await _customerOrderServices.QueryCustomerOrder(query);

                // 判断是否导出全部或当前页
                var exportList = exportAll 
                    ? list.OrderByDescending(a => a.Id).ToList()
                    : query.CurrentPageIds != null && query.CurrentPageIds.Any()
                        ? list.Where(a => query.CurrentPageIds.Contains(a.Id))
                             .OrderBy(a => query.CurrentPageIds.IndexOf(a.Id))  // 保持与页面显示相同的顺序
                             .ToList()
                        : list.Take(query.limit).ToList();

                // 创建工作簿
                IWorkbook b = new XSSFWorkbook();
                ISheet s = b.CreateSheet();

                // 创建表头样式
                ICellStyle headerStyle = b.CreateCellStyle();
                IFont headerFont = b.CreateFont();
                headerFont.IsBold = true;
                headerStyle.SetFont(headerFont);
                headerStyle.Alignment = HorizontalAlignment.Center;
                headerStyle.VerticalAlignment = VerticalAlignment.Center;
                headerStyle.BorderTop = BorderStyle.Thin;
                headerStyle.BorderBottom = BorderStyle.Thin;
                headerStyle.BorderLeft = BorderStyle.Thin;
                headerStyle.BorderRight = BorderStyle.Thin;

                // 创建内容样式
                ICellStyle contentStyle = b.CreateCellStyle();
                contentStyle.Alignment = HorizontalAlignment.Center;
                contentStyle.VerticalAlignment = VerticalAlignment.Center;
                contentStyle.BorderTop = BorderStyle.Thin;
                contentStyle.BorderBottom = BorderStyle.Thin;
                contentStyle.BorderLeft = BorderStyle.Thin;
                contentStyle.BorderRight = BorderStyle.Thin;

                // 创建日期格式样式
                ICellStyle dateCellStyle = b.CreateCellStyle();
                IDataFormat dataFormat = b.CreateDataFormat();
                dateCellStyle.DataFormat = dataFormat.GetFormat("yyyy-MM-dd");
                dateCellStyle.Alignment = HorizontalAlignment.Center;
                dateCellStyle.VerticalAlignment = VerticalAlignment.Center;
                dateCellStyle.BorderTop = BorderStyle.Thin;
                dateCellStyle.BorderBottom = BorderStyle.Thin;
                dateCellStyle.BorderLeft = BorderStyle.Thin;
                dateCellStyle.BorderRight = BorderStyle.Thin;

                // 设置列宽（单位：字符宽度）
                s.SetColumnWidth(0, 20 * 256); // 订单编码
                s.SetColumnWidth(1, 15 * 256); // 客户名称
                s.SetColumnWidth(2, 12 * 256); // 订货日期
                s.SetColumnWidth(3, 12 * 256); // 交货日期
                s.SetColumnWidth(4, 15 * 256); // 规格型号
                s.SetColumnWidth(5, 10 * 256); // 订货数量
                s.SetColumnWidth(6, 8 * 256);  // 单位
                s.SetColumnWidth(7, 15 * 256); // 订单状态
                s.SetColumnWidth(8, 20 * 256); // 质量要求

                // 创建表头
                IRow row1 = s.CreateRow(0);
                row1.Height = 400; // 设置行高

                // 设置表头
                var headers = new[] { "订单编码", "客户名称", "订货日期", "交货日期", "规格型号", "订货数量", "单位", "订单状态", "质量要求" };
                for (int i = 0; i < headers.Length; i++)
                {
                    var cell = row1.CreateCell(i);
                    cell.SetCellValue(headers[i]);
                    cell.CellStyle = headerStyle;
                }

                int index = 1;
                foreach (var item in exportList)
                {
                    IRow row = s.CreateRow(index);
                    row.Height = 350; // 设置数据行高

                    // 设置单元格内容和样式
                    var cell0 = row.CreateCell(0);
                    cell0.SetCellValue(item.OrderCode ?? "");
                    cell0.CellStyle = contentStyle;

                    var cell1 = row.CreateCell(1);
                    cell1.SetCellValue(item.CustomerName ?? "");
                    cell1.CellStyle = contentStyle;

                    var orderTimeCell = row.CreateCell(2);
                    orderTimeCell.SetCellValue(item.OrderTime.Date);
                    orderTimeCell.CellStyle = dateCellStyle;

                    var deliveryCell = row.CreateCell(3);
                    deliveryCell.SetCellValue(item.Delivery.Date);
                    deliveryCell.CellStyle = dateCellStyle;

                    var cell4 = row.CreateCell(4);
                    cell4.SetCellValue(item.Specifications ?? "");
                    cell4.CellStyle = contentStyle;

                    var cell5 = row.CreateCell(5);
                    cell5.SetCellValue(item.OrderCount.ToString());
                    cell5.CellStyle = contentStyle;

                    var cell6 = row.CreateCell(6);
                    cell6.SetCellValue(item.Unit ?? "");
                    cell6.CellStyle = contentStyle;

                    var cell7 = row.CreateCell(7);
                    cell7.SetCellValue(item.OrderStatus ? "已生成生产订单" : "草稿");
                    cell7.CellStyle = contentStyle;

                    var cell8 = row.CreateCell(8);
                    cell8.SetCellValue(item.Requirement ?? "");
                    cell8.CellStyle = contentStyle;

                    index++;
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    b.Write(ms);
                    data = ms.ToArray();
                }

                return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", t);
            }
            catch (Exception ex)
            {
                return Content("导出失败：" + ex.Message);
            }
        }



        /// <summary>
        /// 生产添加退料页面
        /// </summary>
        /// <returns></returns>
        public IActionResult CreateProductionMaterialReturnView()
        {
            return View();
        }

        /// <summary>
        /// 显示生产退料页面
        /// </summary>
        /// <returns></returns>
        public IActionResult ShowProductionMaterialReturnView()
        {
            return View();
        }

        /// <summary>
        /// 修改生产退料页面
        /// </summary>
        /// <returns></returns>
        public IActionResult UpdateProductionMaterialReturnView()
        {
            return View();
        }

        /// <summary>
        /// 添加生产退料
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateProductionMaterialReturn([FromBody] CreateProductionMaterialReturnDto dto)
        {
            var result = await _productionMaterialReturnServices.CreateProductionMaterialReturn(dto);
            return Json(new
            {
                success = result > 0,
                message = result > 0 ? "添加成功" : "添加失败"
            });
        }

        /// <summary>
        /// 查询生产退料
        /// </summary>
        /// <param name="queryDto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryProductionMaterialReturn(GetProductionMaterialReturnDto queryDto)
        {
            var list = await _productionMaterialReturnServices.QueryProductionMaterialReturn(queryDto);
            // 分页处理
            var paged = list.OrderByDescending(a => a.Id)
                            .Skip((queryDto.page - 1) * queryDto.limit)
                            .Take(queryDto.limit)
                            .ToList();
            return Json(new
            {
                code = 0,
                msg = "",
                count = list.Count,
                data = paged
            });
        }

        /// <summary>
        /// 修改生产退料
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateProductionMaterialReturn([FromBody] UpdateProductionMaterialReturnDto dto)
        {
            var result = await _productionMaterialReturnServices.UpdateProductionMaterialReturn(dto);
            return Json(new
            {
                success = result > 0,
                message = result > 0 ? "修改成功" : "修改失败"
            });
        }

        /// <summary>
        /// 批量删除生产退料
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDeleteProductionMaterialReturn([FromBody] List<int> ids)
        {
            if (ids == null || !ids.Any())
                return Json(new { code = 1, msg = "未传递ID" });
            await _productionMaterialReturnServices.BatchDeleteProductionMaterialReturn(ids);
            return Json(new { code = 0, msg = "删除成功" });
        }
       /// <summary>
/// 根据ID获取生产退料单详情
/// </summary>
[HttpGet]
public async Task<IActionResult> GetProductionMaterialReturnById(int id)
{
    var dto = await _productionMaterialReturnServices.GetProductionMaterialReturnById(id);
    if (dto == null)
    {
        return Json(new { code = 1, msg = "未找到数据" });
    }
    return Json(new { code = 0, data = dto });
}

        /// <summary>
        /// 修改退料状态
        /// </summary>
        [HttpPut]
        public async Task<IActionResult> UpProductionMaterialReturnById(int id)
        {
            var result = await _productionMaterialReturnServices.UpProductionMaterialReturnById(id);
            return Json(new
            {
                success = result > 0,
                message = result > 0 ? "退料成功" : "退料失败"
            });
        }
    }
}
